import React, { useContext, useState } from 'react';
import ReactDOM from 'react-dom';

let FormContext = React.createContext()
let ItemContext = React.createContext()

function Form(props) {
  let { children, initialValues, onFinish } = props; // Form.Item...
  return <FormContext.Provider value={{ initialValues, onFinish }}>
    <div className='form_box'>
      {children}
    </div>
  </FormContext.Provider>
}
function Item(props) {
  let { children, label, name } = props; //Input  Button 
  return <ItemContext.Provider value={{ label, name }}>
    <div className='item_box'>
      {children}
    </div>
  </ItemContext.Provider>
}
Form.Item = Item;

function Input() {
  let Item = useContext(ItemContext)// {label,name}
  let Form = useContext(FormContext) // {initValues,onFinishi}
  console.log(Item, Form)
  // let val = Form.initialValues[Item.name];
  let [val, setVal] = useState(Form.initialValues[Item.name])
  return <div className='input_box'>
    {Item.label} <input type="text" value={val} onChange={e => {
      setVal(e.target.value) // 只是改了私有属性val
      Form.initialValues[Item.name] = e.target.value//修改了数据源中的属性
    }} />
  </div>
}

function Button(props) {
  let { children } = props;// 提交
  let Form = useContext(FormContext)
  return <button onClick={() => {
    Form.onFinish()
  }}>{children}</button>
}


class App extends React.Component {
  state = {
    initValue: {
      name: "珠峰",
      age: 13,
      sex: "男"
    }
  }
  onFinish = () => {
    console.log("点击了提交", this.state.initValue)
  }
  render() {
    return <div className=''>
      <Form
        initialValues={this.state.initValue}
        onFinish={this.onFinish}
      >
        <Form.Item
          label="用户名"
          name="name">
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="年龄"
          name="age">
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="性别"
          name="sex">
          <Input></Input>
        </Form.Item>
        <Form.Item>
          <Button>提交</Button>
        </Form.Item>
      </Form>
    </div>;
  }
}

ReactDOM.render(<App />, document.getElementById('root'))